# -*- coding: utf-8 -*-

"""

Created on Fri Mar  2 15:36:44 2018
@author: gg

"""
"""
有时会报错：
ExpatError: not well-formed (invalid token): line 1, column 2
但检查一下坐标是没问题的。
故可以忽略
"""

import xml.dom.minidom

import os

#save_dir = 'F:/图片集/mlt/plate_train'
save_dir = 'E:/labelimage/image1/d-label'
if not os.path.exists(save_dir):
    os.mkdir(save_dir)

#path = 'F:/图片集/mlt/xml3'  # H:\pycharm\ResNet-18-cifar10\learn\originalData\1\
path = 'E:/labelimage/image1/o-label'
filelist = os.listdir(path)
for item in filelist:
    DOMTree = xml.dom.minidom.parse(path+'/'+item) #打开对应的xml文件

    annotation = DOMTree.documentElement           #获取xml文件里面的对象内容

    filename = annotation.getElementsByTagName("filename")[0] #获取filename那一列的地址

    imgname = filename.childNodes[0].data  #获取filename那一列的内容

    file_name = 'gt_'+imgname[:imgname.find('.')]+'.txt' #创建txt文件

    f = open(os.path.join(save_dir, file_name), 'w')     #打开txt

    print(imgname)

    objects = annotation.getElementsByTagName("object") #获取每一行的内容

    loc = []  # 文档保存格式：文件名 坐标

    for object in objects:  #取出每一行的坐标
        bbox = object.getElementsByTagName("bndbox")[0]

        leftTopx = bbox.getElementsByTagName("xmin")[0]

        lefttopx = leftTopx.childNodes[0].data

        print(lefttopx)

        leftTopy = bbox.getElementsByTagName("ymin")[0]

        lefttopy = leftTopy.childNodes[0].data

        print(lefttopy)

        rightTopx = bbox.getElementsByTagName("xmax")[0]

        righttopx = rightTopx.childNodes[0].data

        print(righttopx)

        rightTopy = bbox.getElementsByTagName("ymin")[0]

        righttopy = rightTopy.childNodes[0].data

        print(righttopy)

        rightBottomx = bbox.getElementsByTagName("xmax")[0]

        rightbottomx = rightBottomx.childNodes[0].data

        print(rightbottomx)

        rightBottomy = bbox.getElementsByTagName("ymax")[0]

        rightbottomy = rightBottomy.childNodes[0].data

        print(rightbottomy)

        leftBottomx = bbox.getElementsByTagName("xmin")[0]

        leftbottomx = leftBottomx.childNodes[0].data

        print(leftbottomx)

        leftBottomy = bbox.getElementsByTagName("ymax")[0]

        leftbottomy = leftBottomy.childNodes[0].data

        print(leftbottomy)

        cod = lefttopx+','+lefttopy+','+righttopx+','+ righttopy+','+rightbottomx+','+rightbottomy+','+leftbottomx+','+leftbottomy
        loc.append(cod)

    for i in range(len(loc)):
        f.write(str(loc[i]))
        f.write('\n')
    f.close()
